<?php

namespace common\models;

use common\helpers\Checker;
use common\helpers\Util;
use Yii;

/**
 * This is the model class for table "CouponConfiguration".
 */
class CouponConfiguration extends ActiveRecord {
    
    // 限制条件
    const ConditionAmount = 1;
    const ConditionDate = 2;
    public static $conditionSelector = [
        self::ConditionAmount => ['title' => '金额', 'status' => 'blue'],
        self::ConditionDate => ['title' => '日期', 'status' => 'gray'],
    ];
    
    // 限制条件
    const OperateGet = 'get';
    const OperateLet = 'let';
    const OperateEq = 'eq';
    public static $operateSelector = [
        self::OperateGet => ['title' => '大于等于', 'status' => 'gray'],
        self::OperateLet => ['title' => '小于等于', 'status' => 'gray'],
        self::OperateEq => ['title' => '等于', 'status' => 'blue'],
    ];
    
    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['coupon_id', 'condition', 'operate', 'threshold'], 'required'],
            [['coupon_id', 'condition'], 'integer'],
            [['threshold'], 'string', 'max' => 255],
        ];
    }
    
    /**
     * 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'coupon_id' => '优惠劵编号',
            'condition' => '限制条件',
            'operate' => '比较类型',
            'threshold' => '比较阈值',
        ];
    }
    
    /**
     * 判断优惠劵是否可用
     * @param $params array 判断参数
     * @return boolean
     */
    public function usable($params = [])
    {
        $ckParams = [];
        switch($this->condition) {
            case static::ConditionAmount: {
                if( ! isset($params['amount'])) {
                    return false;
                }
                $rule = [
                    'param' => [
                        'amount' => [['金额', ['int', $this->operate => $this->threshold, 'required']]],
                    ]
                ];
                $ckParams['amount'] = $params['amount'];
            } break;
            case static::ConditionDate: {
                $rule = [
                    'param' => [
                        'date' => [['金额', ['date' => 'Y-m-d', $this->operate => $this->threshold, 'required']]],
                    ]
                ];
                $ckParams['date'] = date('Y-m-d');
            } break;
        }
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return false;
        }
        return true;
    }
    
    /**
     * 批量插入薪酬
     * @return boolean
     */
    public static function batchInsert($params)
    {
        if(empty($params)) {
            return false;
        }
        $columns = ['coupon_id', 'condition', 'operate', 'threshold', 'created_at', 'updated_at'];
        return Util::batchInsert(static::tableName(), $columns, $params, static::getDb());
    }
}
